package com.zt.bus.www.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zt.bus.alipay.util.AlipayUtil;
import com.zt.bus.constant.BusConstant;
import com.zt.bus.order.model.OrderPayment;
import com.zt.bus.order.service.OrderPaymentService;
import com.zt.servlet.Response;
import com.zt.system.model.BusinessException;
import com.zt.util.PropertiesUtil;
import com.zt.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/11.
 */
@Controller
@RequestMapping(value = "/website")
public class AlipayWebPayController {

    @Autowired
    private OrderPaymentService orderPaymentService;

    private static final Logger LOG = Logger.getLogger(AlipayWebPayController.class);

    @RequestMapping(value = "/pay")
    @ResponseBody
    public JSONObject websitePay(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
        LOG.info("开始调起支付!");
        String orderId = httpRequest.getParameter("orderId");
        String phone = httpRequest.getParameter("phone");
        if (StringUtil.isEmpty(orderId) || StringUtil.isEmpty(phone)) {
            throw new BusinessException("缺少请求参数!");
        }

        AlipayClient alipayClient = AlipayUtil.getAlipayClient();
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
        alipayRequest.setReturnUrl("http://investor.lingducapital.com/custom-bus/website/returnUrl.do");
        alipayRequest.setNotifyUrl("http://investor.lingducapital.com/custom-bus/website/notifyUrl.do");// 在公共参数中设置回跳和通知地址
        AlipayTradePagePayModel pagePayModel = new AlipayTradePagePayModel();

        // 得到订单信息
        OrderPayment orderPayment = orderPaymentService.getOrderPayment(BusConstant.PayPlatform.ALIPAY_WEB, orderId,
                phone);
        pagePayModel.setBody("定制公交");
        pagePayModel.setOutTradeNo(orderPayment.getTradeNo());
        pagePayModel.setProductCode("FAST_INSTANT_TRADE_PAY");
        pagePayModel.setSubject("定制公交订单号:" + orderId);
        pagePayModel.setTotalAmount("0.05");
        alipayRequest.setBizModel(pagePayModel);
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
            orderPaymentService.createOrderPayment(orderPayment);
            LOG.info("调起支付成功!");
        } catch (AlipayApiException e) {
            LOG.info("调起支付失败!");
            e.printStackTrace();
        }

        JSONObject json = new JSONObject();
        json.put("form",form);
//        httpResponse.setContentType("text/html;charset=" + AlipayConstants.CHARSET_UTF8);
//        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
        return Response.responseSuccess(json);
    }

    @RequestMapping(value = "/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String tradeNo = request.getParameter("out_trade_no");
        OrderPayment orderPayment = orderPaymentService.getByPrimaryKey(tradeNo);
        if(orderPayment == null) {
            throw new BusinessException("商户订单号不存在!");
        }
        LOG.info("支付宝完成跳转到商户页面!");
        return "redirect:/www/index.html#/user/order/pay/" + orderPayment.getOrderId() + "/1";
    }

    @RequestMapping(value = "/notifyUrl")
    public String notifyUrl(HttpServletRequest request, HttpServletResponse httpResponse) throws IOException {
        LOG.info("支付宝wap版本开始回调");
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            Enumeration<?> pNames = request.getParameterNames();
            Map<String, String> param = new HashMap<String, String>();
            try {
                while (pNames.hasMoreElements()) {
                    String pName = (String) pNames.nextElement();
                    param.put(pName, request.getParameter(pName));
                }
                // 商户订单号
                String out_trade_no = param.get("out_trade_no");
                // 支付宝交易号
                String trade_no = param.get("trade_no");
                boolean signVerified = AlipaySignature.rsaCheckV1(param, AlipayUtil.ALIPAY_PUBLIC_KEY,
                        AlipayConstants.CHARSET_UTF8);
                if (signVerified) {
                    // 验签成功后 处理订单信息
                    // 按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
                    orderPaymentService.paymentSetResult(out_trade_no, trade_no, true, "订单支付通知： 支付成功，订单号"
                            + out_trade_no);
                    LOG.info("订单支付成功：" + JSONObject.fromObject(param));
                    return "SUCCESS";
                } else {
                    // TODO 验签失败则记录异常日志，并在response中返回failure.
                    orderPaymentService.paymentSetResult(out_trade_no, trade_no, false, "订单支付失败，订单号" + out_trade_no);
                    LOG.info("订单支付失败：" + JSONObject.fromObject(param));
                    return "FAILED";
                }
            } catch (Exception e) {
                LOG.info(e.getMessage());
                LOG.info("订单支付失败：" + JSONObject.fromObject(param));
                e.printStackTrace();
            }
        }
        LOG.info("支付宝wap版本回调结束");
        return "SUCCESS";
    }
}
